package models

import (
	"github.com/jinzhu/gorm"
	"time"
)

type SmsValidate struct {
	ID       int    `gorm:"primary_key" json:"id"`
	Type int `json:"type"`
	MobilePhone string `json:"mobile_phone"`
	DeadLine time.Time `json:"dead_line"`
	MsgCode string `json:"msg_code"`
	IsValided int `json:"is_valided"`
	IsSended int `json:"is_sended"`
	TempId string `json:"temp_id"`
	Data string `json:"data"`
	ResultInfo string `json:"result_info"`
	CreatedAt time.Time `json:"created_at"`
	UpdatedAt time.Time `json:"updated_at"`
}

//修改默认表名
func (SmsValidate) TableName() string {
	return "sms_validate"
}


// @Summary 短信验证是否过期
func CheckSMSValidate(phone, code string) (bool, error)  {
	var sms SmsValidate
	err := DB.Select("dead_line").Where(SmsValidate{MobilePhone: phone, MsgCode: code}).Order("`sms_validate`.`id` DESC", true).Find(&sms).Error
	if err != nil && err != gorm.ErrRecordNotFound {
		return false, err
	}
	
	now := time.Now()
	subM := now.Sub(sms.DeadLine) // 当前时间-验证码时间 > 5分钟

	if subM.Minutes() > 5 {
		return false, nil
	}

	return true, nil
}

// 添加
func SMSValidateAdd(data map[string]interface{}) error {

	s := SmsValidate{
		Type : data["type"].(int),
		MobilePhone : data["mobile_phone"].(string),
		DeadLine : data["dead_line"].(time.Time),
		MsgCode : data["msg_code"].(string),
		IsValided : data["is_valided"].(int),
		IsSended : data["is_sended"].(int),
		TempId : data["temp_id"].(string),
		Data : data["data"].(string),
		ResultInfo : data["result_info"].(string),
		CreatedAt: time.Now(),
		UpdatedAt: time.Now(),
	}
	if err := DB.Create(&s).Error; err != nil {
		return err
	}
	

	return nil
}

// 查询短信
func SelectSMSValidate(phone string) (SmsValidate, error)  {
	var sms SmsValidate
	err := DB.Select("*").Where(SmsValidate{MobilePhone: phone}).Order("`sms_validate`.`id` DESC", true).Limit(1).Find(&sms).Error
	
	return sms, err
}
